<?php
/*
 * 文章导入用到的函数库
 * @package    auto
 * @author     Mark
 * @copyright  Copyright (c) 2013 ixdcw team
 * @version    $Id: ffa130b71661ec9fb3731be535b3d9ea86c1b5af $
 */
defined('IN_IXDCW') or exit('Access Denied');
/**
 * Class AutoImport
 */
class AutoImport {

	/**
	 * 根据车系名称获取匹配的系统ID值
	 * @param $kw
	 * @return array
	 */
	public static function match($kw) {
		$rule = DT_ROOT . '/file/dict/matchAutoCategory.rules.utf8.ini';
		$dict = DT_ROOT . '/file/dict/matchAutoCategory.dict.utf8.xdb';
		$scws = new SCWS(SCWS::CHARSET_UTF8, $rule, $dict);
		$kw   = trim($kw);
		$scws->setText($kw);
		$kws = $scws->getTops(5);
		if ($kws) {
			$match = $kws[0];
			if ($match['attr'] == 'en') { // english
				return array(0, 0, 0);
			} else {
				$substr = substr($match['attr'], 0, 1);
				switch ($substr) {
					case 'c':
						$carid   = intval($match['weight']/$match['times']);
						$manuid  = AutoRank::getArmidByArcid($carid);
						$brandid = AutoRank::getArbidByArcid($carid);
						break;
					case 'm':
						$carid   = 0;
						$manuid  = intval($match['weight']/$match['times']);
						$brandid = AutoCategory::getCacheItem(AutoCategory::TYPE_RANK, $manuid, 'parentid');
						break;
					case 'b':
						$carid   = $manuid = 0;
						$brandid = intval($match['weight']/$match['times']);
						break;
					default :
						$carid = $manuid = $brandid = 0;
				}
				return array($brandid, $manuid, $carid);
			}
		} else { // not match
			return array(0, 0, 0);
		}
	}

	/**
	 * 获取车系的文件夹名称
	 * @param $carid
	 * @return string
	 */
	public static function carFolder($carid) {
		global $db;
		$cache  = AutoCategory::getCache(AutoCategory::TYPE_RANK);
		$table  = 'xd_auto_category';
		$root   = array();
		$root[] = 'E:/Folder';
		$r      = $db->getOne("select * from $table where arid = $carid");

		$parentids = explode(',', $r['arrparentid']);
		array_shift($parentids);
		foreach ($parentids as $pid) {
			$root[] = str_replace(array('/', '\\', '*', ':', '"', '?', '<', '>', '|'), '', $cache[$pid]['name']);
		}
		$root[]     = $r['name'];
		$folderUtf8 = implode('/', $root);
		return $folderUtf8;
	}

	/**
	 * 获取车款的文件夹名称
	 * @param $modelid
	 * @return string
	 */
	public static function modelFolder($modelid) {
		global $db;
		$table = 'xd_auto_model';
		$r     = $db->getOne("select * from $table where amid = $modelid");
		return self::carFolder($r['arcid']) . '/' . str_replace(array('/', '\\', '*', ':', '"', '?', '<', '>', '|'), '', $r['name']);
	}

	/**
	 * 生成中文目录
	 * @param $folder
	 */
	public static function mkZhFolder($folder) {
		if (!file_exists($folder)) {
			if (!mkdir($folder, 0777, true)) {
				exit($folder);
			}
		}
	}

	/**
	 * 使用curl获取文件并保存
	 * @param        $url
	 * @param string $file
	 * @return mixed
	 */
	public static function cGet($url, $file = '') {
		$falseIP = rand(1, 255) . '.' . rand(1, 255) . '.' . rand(1, 255) . '.' . rand(1, 255);
		$curl    = curl_init(); // 启动一个CURL会话
		curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
		curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
		curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
		curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
		curl_setopt($curl, CURLOPT_HTTPGET, 1); // 发送一个常规的Post请求
		curl_setopt($curl, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:' . $falseIP, 'CLIENT-IP:' . $falseIP));
		curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
		curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
		$tmpInfo = curl_exec($curl); // 执行操作
		if (curl_errno($curl)) {
			echo 'Errno' . curl_error($curl);
		}
		curl_close($curl); // 关闭CURL会话
		if ($file) {
			File::put($file, $tmpInfo);
		} else {
			return $tmpInfo; // 返回数据
		}
	}

	/**
	 * 获取车系的文件夹名称
	 * @param $carInfo
	 * @param $prefix
	 * @return string
	 */
	public static function carFolderByInfo($carInfo, $prefix = '') {
		$cache     = AutoCategory::getCache(AutoCategory::TYPE_RANK);
		$root      = array();
		$root[]    = $prefix;
		$parentids = explode(',', $carInfo['arrparentid']);
		array_shift($parentids);
		foreach ($parentids as $pid) {
			$root[] = str_replace(array('/', '\\', '*', ':', '"', '?', '<', '>', '|'), '', $cache[$pid]['name']);
		}
		$root[]     = $carInfo['name'];
		$folderUtf8 = implode('/', $root);
		return $folderUtf8;
	}

	/**
	 * 获取车系的文件夹名称
	 * @param $carInfo
	 * @param $prefix
	 * @return string
	 */
	public static function carFolderNoManu($carInfo, $prefix = '') {
		$cache     = AutoCategory::getCache(AutoCategory::TYPE_RANK);
		$root      = array();
		$root[]    = $prefix;
		$parentids = explode(',', $carInfo['arrparentid']);
		array_shift($parentids);
		unset($parentids[1]);
		foreach ($parentids as $pid) {
			$root[] = str_replace(array('/', '\\', '*', ':', '"', '?', '<', '>', '|'), '', $cache[$pid]['name']);
		}
		$root[]     = $carInfo['name'];
		$folderUtf8 = implode('/', $root);
		return $folderUtf8;
	}

	/**
	 * 检测图片匹配类别
	 * @param $relative
	 * @return array|bool
	 */
	public static function pictureMatch($relative) {
		preg_match('/\/(.*?)\/(.*)\.(jpg|gif|png|bmp|jpeg)/', $relative, $match);
		if ($match[1] && $match[2]) {
			$pictures         = AutoCategory::getCache(AutoCategory::TYPE_PICTURE);
			$return           = array();
			$return['typeid'] = 0;
			foreach ($pictures as $picture) {
				if ($picture['name'] == $match[1]) {
					$return['typeid'] = $picture['arid'];
				}
			}
			$descs = explode('-', $match[2]);
			foreach ($descs as $k => $v) {
				if (empty($v) || is_numeric($v)) {
					unset($descs[$k]);
				}
			}
			$return['desc'] = implode(' ', $descs);
			return $return;
		} else {
			return false;
		}
	}

	/**
	 * 检测图片匹配类别
	 * @param $relative
	 * @return array|bool
	 */
	public static function pictureMatchAutohome($relative) {
		preg_match('/\/(.*?)\/(.*)\.(jpg|gif|png|bmp|jpeg)/', $relative, $match);
		if ($match[1] && $match[2]) {
			// 外观 546
			// 内饰 547
			// 空间 548
			// 试驾 549
			// 图解 550
			// 官方图 551
			// 车展 552
			// 活动 553
			// 细节 554
			// 颜色 555

			$matchRules = array(
				'546' => array('车身外观'),
				'547' => array('车厢座椅', '中控方向盘'),
				'548' => array(),
				'549' => array(),
				'550' => array('评测', '图解'),
				'551' => array(),
				'552' => array('活动'),
				'553' => array(),
				'554' => array('改装', '其它细节'),
				'555' => array(),
			);
			$return           = array();
			$return['typeid'] = 0;
			foreach ($matchRules as $typeid => $matched) {
				if (!$return['typeid']) {
					foreach ($matched as $key => $value) {
						if ($value == trim($match[1])) {
							$return['typeid'] = $typeid;
						}
					}
				} else {
					continue;
				}
			}

			$return['desc'] = preg_replace('/___.*/', '', $match[2]);
			return $return;
		} else {
			return false;
		}
	}

	/**
	 * 检测时间字段
	 * @param $time
	 * @return bool
	 */
	public static function checkTime($time) {
		$year = substr($time, 0, 4);
		if ($year < 2012) return false;
		return true;
	}



	/**
	 * 获取时间戳
	 * @param $time
	 * @param $type
	 *          1 2013-07-17 10:07:56
	 *          2 2013-07-17
	 * @return int
	 */
	public static function getTime($time, $type) {

		if ($type == 1) {
			$format = "Y-m-d H:i:s";
		} else if ($type == 2) {
			$format = "Y-m-d";
		}else if ($type == 3) {
			$format = "Y年m月d日";
		}else if ($type == 4) {
			$format = "Y年m月d日 H:i";
		} else if ($type == 5) {
			$format = "Y-m-d H:i";
		}
		$date = DateTime::createFromFormat($format, $time);
		return $date->getTimestamp();
	}

	/**
	 * 保存远程
	 * @param        $content
	 * @param string $ext
	 * @param int    $moduleid
	 * @param int    $userid
	 * @param string $time
	 * @param string $picAdd
	 * @return mixed
	 */
	public static function saveRemotes($content, $ext = 'jpg|jpeg|gif|png|bmp|swf', $moduleid = 0, $userid = 1, $time = '', $picAdd = '') {

		global $DT, $CFG, $v;
		if (!$userid || !$content) return $content;
		$content = stripcslashes($content);
		if (!preg_match_all("/src=([\"|']?)([^ \"'>]+\.($ext))\\1/i", $content, $matches)) return $content;

		$urls = $oldpath = $newpath = array();

		foreach ($matches[2] as $k => $url) {
			if (in_array($url, $urls)) continue;
			$oldPath = $url;
			if (strpos($url, 'http://') === false) {
				$url = $picAdd . $url;
				$url = preg_replace("/(http:\/\/\/\/.*)(\/\/)(.*)/", '$1/$3', $url);
			}
			$urls[$url] = $url;
			if (strpos($url, '://') === false) continue;
			if (strpos($url, '.' . $CFG['domain'] . '/') !== false) continue;
			$file_ext = File::ext($url);
			if (!$time) {
				$time = time();
			}

			$relative = Picture::name($moduleid, $userid, $file_ext, $time);

			if ($CFG['ftp2_user']) {
				// save to ftp temp
				$aim      = DT_CACHE . '/ftp/' . basename($relative);
				$ftpLocal = $aim;
			} else {
				// save to local and check file
				$aim = U::realpath(U::DOMAIN_IMG1) . '/' . $relative;
			}
			if (File::curlGet($url, $aim)) {
				if (Post::isImage($aim)) {
					if (!@getimagesize($aim)) {
						File::del($aim);
						continue;
					}
				}
				if ($CFG['ftp2Img']) {
					// then save to ftp
					$ftpAim = $relative;
					$config = array(
						'hostname' => $CFG['ftp2_host'],
						'username' => $CFG['ftp2_user'],
						'password' => $CFG['ftp2_pass'],
						'port' => 21
					);
					try{
						$ftp    = new newFtp();
						$ftp->connect($config);
						if (!$ftp->chgdir(dirname($ftpAim))) {
							$ftp->mkdir(dirname($ftpAim));
						}
						$ftp->upload($ftpLocal,basename($ftpAim));
						File::del($ftpLocal);
					}catch (Exception $e){
						echo $e;
						exit;
					}
				}
				$oldpath[] = $oldPath;
				$newpath[] = Picture::url($relative);
			}

		}
		unset($matches);
		return str_replace($oldpath, $newpath, $content);
	}


	/**
	 * 保存远程
	 * @param        $content
	 * @param string $ext
	 * @param int    $moduleid
	 * @param int    $userid
	 * @param string $time
	 * @param string $picAdd
	 * @return mixed
	 */
	public static function saveRemote($content, $ext = 'jpg|jpeg|gif|png|bmp|swf', $moduleid = 0, $userid = 1, $time = '', $picAdd = '') {
		global $DT, $CFG, $v;
		if (!$userid || !$content) return $content;
		if (!preg_match_all("/src=([\"|']?)([^ \"'>]+\.($ext))\\1/i", $content, $matches)) return $content;
		$urls = $oldpath = $newpath = array();

		foreach ($matches[2] as $k => $url) {
			if (in_array($url, $urls)) continue;
			$oldPath = $url;
			if (strpos($url, 'http://') === false) {
				$url = $picAdd . $url;
				$url = preg_replace("/(http:\/\/\/\/.*)(\/\/)(.*)/", '$1/$3', $url);
			}
			$urls[$url] = $url;
			if (strpos($url, '://') === false) continue;
			if (strpos($url, '.' . $CFG['domain'] . '/') !== false) continue;
			$file_ext = File::ext($url);
			if (!$time) {
				$time = time();
			}
			$relative = Picture::name($moduleid, $userid, $file_ext, $time);

			if ($CFG['ftp2Img']) {
				// save to ftp temp
				$aim      = DT_CACHE . '/ftp/' . basename($relative);
				$ftpLocal = $aim;
			} else {
				// save to local and check file
				$aim = U::realpath(U::DOMAIN_IMG1) . '/' . $relative;
			}

			if (File::curlGet($url, $aim)) {
				if (Post::isImage($aim)) {
					if (!@getimagesize($aim)) {
						File::del($aim);
						continue;
					}
				}


				if ($CFG['ftp2Img']) {
					// then save to ftp
					$ftpAim = $relative;
					$ftp    = new Ftp($CFG['ftp2Img']);
					if (!$ftp->isDir(dirname($ftpAim))) {
						$ftp->mkDirRecursive(dirname($ftpAim));
					}
					$ftp->put($ftpAim, $ftpLocal, FTP_BINARY);
					File::del($ftpLocal);
				}
				$oldpath[] = $oldPath;
				$newpath[] = Picture::url($relative);
			}
		}
		unset($matches);
		return str_replace($oldpath, $newpath, $content);
	}

	public static function fullUrl($content, $ext = 'jpg|jpeg|gif|png|bmp', $picAdd = '') {
		if (!$content) return $content;
		if (!preg_match_all("/src=([\"|']?)([^ \"'>]+\.($ext))\\1/i", $content, $matches)) return $content;
		$urls = $oldpath = $newpath = array();

		foreach ($matches[2] as $url) {
			if (in_array($url, $urls)) continue;
			$oldPath = $url;
			if (strpos($url, 'http://') === false) {
				$url = $picAdd . $url;
				$url = preg_replace("/(http:\/\/\/\/.*)(\/\/)(.*)/", '$1/$3', $url);
			}
			$oldpath[] = $oldPath;
			$newpath[] = $url;
		}
		unset($matches);
		return str_replace($oldpath, $newpath, $content);
	}

	/**
	 * 保存缩略图
	 * @param        $content
	 * @param        $no
	 * @param int    $width
	 * @param int    $height
	 * @param int    $moduleid
	 * @param int    $userid
	 * @param string $time
	 * @param string $picAdd
	 * @return string
	 */
	public static function saveThumb($content, $no, $width = 120, $height = 90, $moduleid = 0, $userid = 1, $time = '', $picAdd = '') {
		global $DT, $CFG, $v;
		if (!$userid || !$content) return '';
		$ext = 'jpg|jpeg|gif|png|bmp';
		if (!preg_match_all("/src=([\"|']?)([^ \"'>]+\.($ext))\\1/i", $content, $matches)) return '';

		foreach ($matches[2] as $k => $url) {

			if ($k == $no - 1) {
				if (strpos($url, 'http://') === false) {
					$url = $picAdd . $url;
					$url = preg_replace("/(http:\/\/\/\/.*)(\/\/)(.*)/", '$1/$3', $url);
				}
				$file_ext = File::ext($url);
				if (!$time) {
					$time = time();
				}

				$originName = Picture::name($moduleid, $userid, $file_ext, $time);
				$thumbName  = Picture::name($moduleid, $userid, $file_ext, $time);

				$ftpTmp   = DT_CACHE . '/ftp/' . basename($originName);
				$ftpThumb = DT_CACHE . '/ftp/' . basename($thumbName);

				$fileAim = Picture::realpath($thumbName);
				if (File::cGet($url, $ftpTmp)) {
					if (Post::isImage($ftpTmp)) {
						if (!@getimagesize($ftpTmp)) {
							File::del($ftpTmp);
							continue;
						}
					}
					$image = new image($ftpTmp);
					$image->thumb($width, $height, 1, $ftpThumb);
					File::del($ftpTmp);
					if ($CFG['ftp2Img']) {
						// then save to ftp
						$ftpAim = Picture::relative($fileAim);
						$ftp    = new Ftp($CFG['ftp2Img']);
						if (!$ftp->isDir(dirname($ftpAim))) {
							$ftp->mkDirRecursive(dirname($ftpAim));
						}
						$ftp->put($ftpAim, $ftpThumb, FTP_BINARY);
					} else {
						if (!File::copyto($ftpThumb, $fileAim)) {
							echo "Move '$ftpThumb' To '$fileAim' Failed";
							exit();
						}
						File::del($ftpThumb);
					}
				}
				return Picture::url($thumbName);
			}
		}
		unset($matches);
		return '';
	}

	/**
	 * 保存缩略图
	 * @param        $content
	 * @param        $no
	 * @param int    $width
	 * @param int    $height
	 * @param int    $moduleid
	 * @param int    $userid
	 * @param string $time
	 * @param string $picAdd
	 * @return string
	 */
	public static function saveThumbs($content, $no, $width = 120, $height = 90, $moduleid = 0, $userid = 1, $time = '', $picAdd = '') {
		global $DT, $CFG, $v;
		if (!$userid || !$content) return '';
		$ext = 'jpg|jpeg|gif|png|bmp';
		$content = stripcslashes($content);
		if (!preg_match_all("/src=([\"|']?)([^ \"'>]+\.($ext))\\1/i", $content, $matches)) return '';

		foreach ($matches[2] as $k => $url) {

			if ($k == $no - 1) {
				if (strpos($url, 'http://') === false) {
					$url = $picAdd . $url;
					$url = preg_replace("/(http:\/\/\/\/.*)(\/\/)(.*)/", '$1/$3', $url);
				}
				$file_ext = File::ext($url);
				if (!$time) {
					$time = time();
				}

				$originName = Picture::name($moduleid, $userid, $file_ext, $time);
				$thumbName  = Picture::name($moduleid, $userid, $file_ext, $time);

				$ftpTmp   = DT_CACHE . '/ftp/' . basename($originName);
				$ftpThumb = DT_CACHE . '/ftp/' . basename($thumbName);

				$fileAim = Picture::realpath($thumbName);
				if (File::cGet($url, $ftpTmp)) {
					if (Post::isImage($ftpTmp)) {
						if (!@getimagesize($ftpTmp)) {
							File::del($ftpTmp);
							continue;
						}
					}
					$image = new image($ftpTmp);
					$image->thumb($width, $height, 1, $ftpThumb);
					File::del($ftpTmp);
					if ($CFG['ftp2_user']) {
						$ftpAim = Picture::relative($fileAim);
						$config = array(
							'hostname' => $CFG['ftp2_host'],
							'username' => $CFG['ftp2_user'],
							'password' => $CFG['ftp2_pass'],
							'port' => 21
						);
						try{
							$ftp    = new newFtp();
							$ftp->connect($config);
							if (!$ftp->chgdir(dirname($ftpAim))) {
								$ftp->mkdir(dirname($ftpAim));

							}
							$ftp->upload($ftpThumb,basename($ftpAim));
							File::del($ftpThumb);
						}catch (Exception $e){
							echo $e;
							exit;
						}

						File::del($ftpThumb);
					}
				}
				return Picture::url($thumbName);
			}
		}
		unset($matches);
		return '';
	}

}

